package com.cloudcc.boot.core;

import cn.hutool.core.bean.BeanUtil;
import com.cloudcc.boot.model.FileRequest;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import jakarta.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author T.han
 * @date 2023/8/17 15:09
 * @project CloudccNewPro
 * @Description //TODO
 */
@Slf4j
public class CCService {
    public static UserInfo userInfo;
    public String ACCESSTOKEN;
    public String path;
    public String URL;
    public String filepath;

    ResourceBundle prb = PropertyResourceBundle.getBundle("application-dev");// 获取配置文件;
    String orgId = prb.getString("system.orgId");

    public CCService(UserInfo userInfo) {
        this.URL = prb.getString("system.url");
        this.ACCESSTOKEN = getToken();
        this.path = URL+ "/openApi/common";
        this.filepath = URL+ "openApi/file";

    }

    public static void main(String[] args) throws Exception {
        CCService cs = new CCService(userInfo);

//        List<CCObject> rel_cquery = cs.cquery("ccuser","isusing=0");
//        log.info("rel_cquery = " + rel_cquery);

//        String userSql = "select * from Event where ownerid='00520246A6B2E1DDNVyP' and ownerid='0052017BE8702F1PIi4j' and createdate>=to_date('2024-07-22','yyyy-mm-dd') and createdate<=to_date('2024-07-28','yyyy-mm-dd')";
        //根据文件ID查询文件表
//        String fileid = "fil20244B8FF7E8SgQBA";
//        String userSql = "select id from xtsyqk where is_deleted=0 and to_char(ksrq,'yyyy-mm-dd')='2024-08-01' and to_char(jsrq,'yyyy-mm-dd')='2024-08-31' and ssqy = '华东'";
//        String userSql = "select id,label,schemetable_name from TP_SYS_OBJECT";//查询所有对象id,对象API,对象名称
//        String userSql = "select id,apiname from TP_SYS_SCHEMETABLE where schemetable_id='202526E41AFD984APudb'";//查询某对象下所有字段，schemetable_id为对象ID
//        String userSql = "select  id,name from cloudcclead where qzkhzt='关闭-已转换'";
//        String userSql = "select count(*) from Opportunity where is_deleted=0 and ssjt='a932024F999E63AguVeJ'";
//        String userSql = "update Account set ssjt='a9320240A3A268DdVK7P' where is_deleted=0 and ssjt='a9320241D6DA9EBaGFLT'";
//        String userSql = "update tp_sys_schemetable set schemefield_length='255' where id='ffe2024FD6FC989ktoPJ'";
//        String userSql = "select * from tp_sys_schemetable where id='ffe2024FD6FC989ktoPJ'";
//        String userSql = "select userid,login_user,count(*) sumNum from tp_sys_login_history where userid!='0052017BE8702F1PIi4j' and to_date(to_char(login_time,'yyyy-mm-dd'),'yyyy-mm-dd')>=to_date('2024-09-01','yyyy-mm-dd') and to_date(to_char(login_time,'yyyy-mm-dd'),'yyyy-mm-dd')<=to_date('2024-09-30','yyyy-mm-dd') group by userid,login_user";
//        String userSql = "select u.id,u.name,DATEDIFF(now(),max(his.login_time)) AS days_difference from tp_sys_user u,tp_sys_login_history his where u.id=his.userid group by u.id,u.name";
//        String userSql = "select * from cloudccskjh where id = '01920256660DF36cGdH2'";
//        String userSql = "select * from Task where id='bfa2025B0D8E08E3Sf9z'";
//        String userSql = "select r.recordname from recordtype r where r.id = '2024386571A80EDq40dh'";
//        String userSql = "select sqmx.wzmc wzmc,wz.name wzmcccname,sum(IFNULL(sqmx.lysl,0)) lysl from wzlysqmx sqmx left join materialledger wz on wz.id=sqmx.wzmc where sqmx.is_deleted=0 and wz.is_deleted=0 and sqmx.lybh='a1620246855711DiP0Uw' group by sqmx.wzmc";
//        String userSql = "update Opportunity set jieduan='6-已签约/核准/备案' where is_deleted=0 and recordtype = '20244284EB89330idX1e' and jieduan='6-赢单'";
//        String userSql = "select id,roleid,rolename from tp_sys_role where gap='0'";//查询角色
//        String userSql = "select id,profilename from tp_sys_profile";//查询简档
//        String userSql = "update Account set recordtype='2019593FC86B601GFelY' where 1=1 and is_deleted=0 and sfjtkh = '是'";//
//        String userSql = "select task.belongtoid,user.name,count(*) num from Task task left join ccuser user on user.id=task.belongtoid  where task.is_deleted=0 and task.xsmc is not null group by task.belongtoid";//查询简档
//        String userSql = "select count(id) from Contact where is_deleted = 0 and recordtype is null";//查询联系人
//        String userSql = "update Contact set recordtype = '2024A6AD5425C02jHuyE' where is_deleted = 0 and ownerid='0052017BE8702F1PIi4j'";//查询联系人
//        String userSql = "update Account set is_deleted='1' where 1=1 and is_deleted=0 and sfjtkh = '是'";//
//        String userSql = "update Contact set is_deleted='1' where 1=1 and ownerid='0052017BE8702F1PIi4j'";//
//        String userSql = "update tp_sys_user set email=''  where login_name='014200005348'";//查询
//        String userSql = "select  id,name from tp_sys_user where EMPLOYEE_NUM is null";
//        String userSql = "select id,name,sortorder from Account where 1=1 and sortorder is not null";
//        String userSql = "select id,name,pwd from tp_sys_user where login_name='014200005144'";
//        String userSql = "select name from tp_sys_user where manager='0052024799D6D03ZF1IN'";
//        String userSql = "select * from tp_sys_user where login_name !='admin@cloudcc.com' and isusing = 1";
//        String userSql = " update tp_sys_user set isusing=0 where login_name !='admin@cloudcc.com'";
//        String userSql = " update tp_sys_user set manager='005202493DC762BblhwT' where login_name = 'W1099'";
        String userSql = " update tp_sys_user set pwd='493341d3dbbfffa2c8d02f1933868a4c' where login_name = '014200006407'";
//        String userSql = " select * from tendermanagement where id = 'a06202503FCE051yFiUZ'";
//        String userSql = " update bjfgpzb set name = '标准流程' where name = '20250902005'";
//        String userSql = " select r.id from tp_sys_user r where r.login_name = '014200005627'";
//        String userSql = "select * from tp_sys_user where login_name='014200007531'";
//        String userSql = "update tp_sys_user set EMPLOYEE_NUM = login_name where EMPLOYEE_NUM is null";
//        String userSql = "select id,name,login_name,ISFIRSTLOGIN from tp_sys_user where pwd='493341d3dbbfffa2c8d02f1933868a4c'";
//        String userSql = "select id,name,login_name,ISFIRSTLOGIN from tp_sys_user where LOGIN_NAME ='014200007736'";
//        String userSql = "select id,name,loginname,useremail,email from ccuser where useremail is not null and useremail !='test@cloudcc.com'";
//        String userSql = "update tp_sys_user set ISFIRSTLOGIN = 'true' where id='0052025EEE89665fu4y6'";
//        String userSql = "update tp_sys_user set pwd='493341d3dbbfffa2c8d02f1933868a4c' where pwd='96e79218965eb72c92a549dd5a330112'";
        List<CCObject> rel_cqlQuery = cs.cqlQuery("Lead", userSql);
        log.info("rel_cqlQuery==size{}==={}", rel_cqlQuery.size(), rel_cqlQuery);
    }


    /**
     * @return java.lang.String
     * @Description //TODO 获取公有云api网关地址
     * @Author T.han
     * @Date 2023/8/17 15:48
     * @Param
     **/
    public String getOrgApiUrl() {
        String apiUrl = "";
        String url = prb.getString("system.url");
        String parUrl = url + "?scope=cloudccCRM&orgId=" + orgId;
        String relStr = sendGet(parUrl);
        JSONObject relObj = new JSONObject();
        relObj = JSONObject.fromObject(relStr);
        String result = relObj.getString("result");
        if ("true".equals(result)) {
            apiUrl = relObj.getString("orgapi_address");
        }
        return apiUrl;
    }

    /**
     * @return java.lang.String
     * @Description //TODO 获取token
     * @Author T.han
     * @Date 2023/8/17 16:10
     * @Param
     **/
    public String getToken() {
        String accessToken = "";
        String username = prb.getString("system.userName");
        String safetyMark = prb.getString("system.safetyMark");
        String clientId = prb.getString("system.clientId");
        String secretKey = prb.getString("system.secretKey");
        String grant_type = prb.getString("system.grant_type");
        //拼接 parObj 参数
        JSONObject parObj = new JSONObject();
        parObj.put("username", username);
        parObj.put("safetyMark", safetyMark);
        parObj.put("clientId", clientId);
        parObj.put("secretKey", secretKey);
        parObj.put("orgId", orgId);
        parObj.put("grant_type", grant_type);
        path= URL+ "api/cauth/token";
        String teststr = parObj.toString();
        if (!"".equals(path)) {
            String relStr = sendPost(path, parObj.toString());
            JSONObject relObj = new JSONObject();
            relObj = JSONObject.fromObject(relStr);
            String result = relObj.getString("result");
            if ("true".equals(result)) {
                accessToken = JSONObject.fromObject(relObj.getString("data")).getString("accessToken");
                log.info("CCService-->getToken():"+accessToken);
            } else {
                String returnInfo = relObj.getString("returnInfo");
                System.out.println("CCService.getToken报错：" + returnInfo);
            }
        } else {
            System.out.println("CCService.getToken报错：未获取到网关地址");
        }
        return accessToken;
    }

    /**
     * @return java.util.List<com.cloudcc.newxm.util.CCObject>
     * @Description //TODO  cquery 查询不加条件
     * @Author T.han
     * @Date 2023/8/17 16:38
     * @Param apiName  对象名
     **/
    public List<CCObject> cquery(String apiName) {
        List<CCObject> orst = new ArrayList<CCObject>();
        //拼接 parObj 参数
        JSONObject parObj = new JSONObject();
        parObj.put("serviceName", "cquery"); //服务名
        parObj.put("objectApiName", apiName); //对象名
        parObj.put("expressions", "1=1"); //查询条件
        parObj.put("isAddDelete", "false"); //是否包含删除数据  true:包含   false:不包含
        parObj.put("fields", "");//查询字段  不填写时sql按 * 返回

//        String path = getOrgApiUrl() + "/openApi/common";
        String relStr = CCPost(path, parObj.toString());
        JSONObject relObj = new JSONObject();
        relObj = JSONObject.fromObject(relStr);
        String result = relObj.getString("result");
        if ("true".equals(result)) {
            List<Map> rst = relObj.getJSONArray("data");
            for (Map m : rst) {
                CCObject co = new CCObject(apiName);
                for (Object _key : m.keySet()) {
                    String key = (String) _key;
                    co.put(key, m.get(key));
                }
                orst.add(co);
            }
        }
        return orst;
    }

    /**
     * @return java.util.List<com.cloudcc.newxm.util.CCObject>
     * @Description //TODO cquery 查询方法
     * @Author T.han
     * @Date 2023/8/17 16:42
     * @Param apiName 对象名
     * @Param expression  查询条件
     **/
    public List<CCObject> cquery(String apiName, String expression) {
        List<CCObject> orst = new ArrayList<CCObject>();
        //拼接 parObj 参数
        JSONObject parObj = new JSONObject();
        parObj.put("serviceName", "cquery"); //服务名
        parObj.put("objectApiName", apiName); //对象名
        parObj.put("expressions", expression); //查询条件
        parObj.put("isAddDelete", "false"); //是否包含删除数据  true:包含   false:不包含
        parObj.put("fields", "");//查询字段  不填写时sql按 * 返回

        String relStr = CCPost(path, parObj.toString());
        JSONObject relObj = new JSONObject();
        relObj = JSONObject.fromObject(relStr);
        String result = relObj.getString("result");
        String data = relObj.getString("data");
        if ("true".equals(result) && !"null".equals(data)) {
            List<Map> rst = relObj.getJSONArray("data");
            for (Map m : rst) {
                CCObject co = new CCObject(apiName);
                for (Object _key : m.keySet()) {
                    String key = (String) _key;
                    co.put(key, m.get(key));
                }
                orst.add(co);
            }
        }
        return orst;
    }

    /**
     * @return java.util.List<com.cloudcc.newxm.util.CCObject>
     * @Description //TODO cqlQuery 查询方法
     * @Author T.han
     * @Date 2023/8/17 16:41
     * @Param apiName  对象名
     * @Param expression  查询sql
     **/
    public List<CCObject> cqlQuery(String apiName, String expression) {
        List<CCObject> orst = new ArrayList<CCObject>();
        //拼接 parObj 参数
        JSONObject parObj = new JSONObject();
        parObj.put("serviceName", "cqlQueryWithLogInfo"); //服务名
        parObj.put("objectApiName", apiName); //对象名
        parObj.put("expressions", expression); //查询条件
        //拼接接口地址
//        String path = getOrgApiUrl() + "/openApi/common";
        String relStr = CCPost(path, parObj.toString());
//        log.info("cqlQuery:-----------"+relStr);
        JSONObject relObj = new JSONObject();
        relObj = JSONObject.fromObject(relStr);
        String result = relObj.getString("result");
//        String data = relObj.getString("data");
        if ("true".equals(result) && !"null".equals( relObj.getString("data"))) {
            List<Map> rst = relObj.getJSONArray("data");
            for (Map m : rst) {
                CCObject co = new CCObject(apiName);
                for (Object _key : m.keySet()) {
                    String key = (String) _key;
                    co.put(key, m.get(key));
                }
                orst.add(co);
            }
        }
        return orst;
    }

    /**
     * @Description //TODO update方法
     * @Author T.han
     * @Date 2023/8/18 10:02
     * @Param cobj
     * @return void
     **/
    public void update(CCObject cobj) {
        JSONArray arry = new JSONArray();
        JSONObject obj = new JSONObject();
        String objectApiName = "";
        for (Object _key : cobj.keySet()) {
            if ("CCObjectAPI".equals(_key)) {
                objectApiName = cobj.get("CCObjectAPI") == null ? "" : cobj.get("CCObjectAPI") + "";
            } else {
                String values = cobj.get(_key) == null ? "" : cobj.get(_key) + "";
                obj.put(_key, values);
            }
        }
        arry.add(obj);
        String arryStr = "\"" + arry + "\"";

        //拼接 parObj 参数
        JSONObject parObj = new JSONObject();
        parObj.put("serviceName", "update"); //服务名
        parObj.put("objectApiName", objectApiName); //对象名
        parObj.put("data", arryStr); //查询条件

//        System.out.println("parObj = " + parObj);
        //拼接接口地址
//        String path = getOrgApiUrl() + "/openApi/common";
        try {
            String relStr = CCPost(path, parObj.toString());
//            System.out.println("relStr = " + relStr);
//            JSONObject relObj = new JSONObject();
//            relObj = JSONObject.fromObject(relStr);
//            String result = relObj.getString("result");
//            if ("true".equals(result)) {
//            }
        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println("update报错= " + e);
        }
    }

    /**
     * @Description //TODO  insert 方法
     * @Author T.han
     * @Date 2023/8/18 10:27
     * @Param cobj 新建 json参数
     * @return com.cloudcc.newxm.util.ServiceResult  返回新建数据id
     **/
    public ServiceResult insert(CCObject cobj) {
        ServiceResult sr = new ServiceResult();
        JSONArray arry = new JSONArray();
        JSONObject obj = new JSONObject();
        String objectApiName = "";
        for (Object _key : cobj.keySet()) {
            if ("CCObjectAPI".equals(_key)) {
                objectApiName = cobj.get("CCObjectAPI") == null ? "" : cobj.get("CCObjectAPI") + "";
            } else {
                String values = cobj.get(_key) == null ? "" : cobj.get(_key) + "";
                obj.put(_key, values);
            }
        }
//        cobj.remove("CCObjectAPI");
        arry.add(obj);
        String arryStr = "\"" + arry + "\"";
        //拼接 parObj 参数
        JSONObject parObj = new JSONObject();
        parObj.put("serviceName", "insert"); //服务名
        parObj.put("objectApiName", objectApiName); //对象名
        parObj.put("data", arryStr); //查询条件
//        System.out.println("parObj = " + parObj);
        //拼接接口地址
//        String path = getOrgApiUrl() + "/openApi/common";
        try {
            String relStr = CCPost(path, parObj.toString());
//            System.out.println("insert_relStr = " + relStr);
            JSONObject relObj = new JSONObject();
            relObj = JSONObject.fromObject(relStr);
            String result = relObj.getString("result");
            if ("true".equals(result)) {
                JSONArray outData = relObj.getJSONObject("data").getJSONArray("ids");
                JSONObject acc = JSONObject.fromObject(outData.getJSONObject(0));
                if(acc.getBoolean("success")){
                    sr.put("id",acc.getString("id"));
                }
            }
        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println("insert报错= " + e);
        }
        return sr;
    }

    /**
     * @Description //TODO 删除方法
     * @Author T.han
     * @Date 2023/8/18 10:38
     * @Param cobj 参数数据 {“id”:"a1231111"}
     * @return void
     **/
    public void delete(CCObject cobj) {
        JSONArray arry = new JSONArray();
        JSONObject obj = new JSONObject();
        String objectApiName = "";
        for (Object _key : cobj.keySet()) {
            if ("CCObjectAPI".equals(_key)) {
                objectApiName = cobj.get("CCObjectAPI") == null ? "" : cobj.get("CCObjectAPI") + "";
            } else {
                String values = cobj.get(_key) == null ? "" : cobj.get(_key) + "";
                obj.put(_key, values);
            }
        }
//       cobj.remove("CCObjectAPI");
        arry.add(obj);
        String arryStr = "\"" + arry + "\"";
        //拼接 parObj 参数
        JSONObject parObj = new JSONObject();
        parObj.put("serviceName", "delete"); //服务名
        parObj.put("objectApiName", objectApiName); //对象名
        parObj.put("data", arryStr); //查询条件
//        System.out.println("parObj = " + parObj);
        //拼接接口地址
//        String path = getOrgApiUrl() + "/openApi/common";
        try {
            String relStr = CCPost(path, parObj.toString());
//            System.out.println("delete_relStr = " + relStr);
//            JSONObject relObj = new JSONObject();
//            relObj = JSONObject.fromObject(relStr);
//            String result = relObj.getString("result");
//            if ("true".equals(result)) {
//                JSONArray outData = relObj.getJSONObject("data").getJSONArray("ids");
//                JSONObject acc = JSONObject.fromObject(outData.getJSONObject(0));
//                if(acc.getBoolean("success")){
//
//                }
//            }
        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println("delete报错= " + e);
        }
    }


    public ServiceResult upsert(CCObject cobj) {
        ServiceResult sr = new ServiceResult();
        JSONArray arry = new JSONArray();
        JSONObject obj = new JSONObject();
        String objectApiName = "";
        for (Object _key : cobj.keySet()) {
            if ("CCObjectAPI".equals(_key)) {
                objectApiName = cobj.get("CCObjectAPI") == null ? "" : cobj.get("CCObjectAPI") + "";
            } else {
                String values = cobj.get(_key) == null ? "" : cobj.get(_key) + "";
                obj.put(_key, values);
            }
        }
//        cobj.remove("CCObjectAPI");
        arry.add(obj);
        String arryStr = "\"" + arry + "\"";
        //拼接 parObj 参数
        JSONObject parObj = new JSONObject();
        parObj.put("serviceName", "upsert"); //服务名
        parObj.put("objectApiName", objectApiName); //对象名
        parObj.put("data", arryStr); //查询条件
//        System.out.println("parObj = " + parObj);
        //拼接接口地址
//        String path = getOrgApiUrl() + "/openApi/common";
        try {
            String relStr = CCPost(path, parObj.toString());
//            System.out.println("insert_relStr = " + relStr);
            JSONObject relObj = new JSONObject();
            relObj = JSONObject.fromObject(relStr);
            String result = relObj.getString("result");
            if ("true".equals(result)) {
                JSONArray outData = relObj.getJSONObject("data").getJSONArray("ids");
                JSONObject acc = JSONObject.fromObject(outData.getJSONObject(0));
                if(acc.getBoolean("success")){
                    sr.put("id",acc.getString("id"));
                }
            }
        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println("upsert报错= " + e);
        }
        return sr;
    }





    /**
     * @Description //TODO post请求
     * @Author T.han
     * @Date 2023/8/18 10:03
     * @Param path  接口地址 http://127.0.0.1/cloudcc/outken
     * @Param param 参数 json
     * @Param IsToken headers是否添加token  false：不添加   true:添加
     * @return java.lang.String
     **/
    public String sendPost(String path, String param) {
        OutputStreamWriter out = null;
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();
        String exception = "";
        String result = "";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = null;
            // 打开和URL之间的连接
            conn = (HttpURLConnection) url.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");    // POST方法
            conn.setConnectTimeout(15 * 1000);// 设置连接超时时间为5秒
            conn.setReadTimeout(20 * 1000);// 设置读取超时时间为20秒
            String tokens = "";
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("accept", "*/*");
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream());
            // 发送请求参数
            BufferedWriter bw = new BufferedWriter(out);
            bw.write(param);
            // flush输出流的缓冲
            bw.flush();
            // 定义BufferedReader输入流来读取URL的响应
            br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            exception = "发送 POST 请求出现异常！" + e;
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        if (sb.toString().isEmpty()) {
            result = exception;
        } else {
            result = sb.toString();
        }
        return result;
    }

    /**
     * 调用标准文件下载接口，输出流
     * @param httpurl
     * @param response
     */
    public void Get(String httpurl,String fileName, HttpServletResponse response) {  //GET
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            //connection.setRequestProperty("x-wlk-Authorization",token);
            connection.setRequestProperty("accessToken",ACCESSTOKEN);
            // 发送请求
            connection.connect();

            response.reset();
            response.setContentType("application/octet-stream");//这里可以设置具体的文件类型
            response.setHeader("Content-Disposition", "attachment; filename=\""+new String(fileName.getBytes("utf-8"),"iso-8859-1")+"\"");//测试可以改成文件名称
            //response.setCharacterEncoding("UTF-8");
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                OutputStream os = response.getOutputStream();
                byte[] buf = new byte[8192];
                int readByte = 0;
                while ((readByte = is.read(buf, 0, buf.length)) > 0) {
                    os.write(buf, 0, readByte);
                    os.flush();
                }
                os.close();
            }
        } catch (MalformedURLException e) {
            result =  e.getMessage().toString();
        } catch (IOException e) {
            result =  e.getMessage().toString();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    result =  e.getMessage().toString();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    result =  e.getMessage().toString();
                }
            }

            connection.disconnect();// 关闭远程连接
        }

    }

    public String CCPost(String path, String param) {
        OutputStreamWriter out = null;
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();
        String exception = "";
        String result = "";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = null;
            // 打开和URL之间的连接
            conn = (HttpURLConnection) url.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");    // POST方法
            conn.setConnectTimeout(15 * 1000);// 设置连接超时时间为5秒
            conn.setReadTimeout(20 * 1000);// 设置读取超时时间为20秒
            String tokens = "";
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("accessToken", ACCESSTOKEN);
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream());
            // 发送请求参数
            BufferedWriter bw = new BufferedWriter(out);
            bw.write(param);
            // flush输出流的缓冲
            bw.flush();
            // 定义BufferedReader输入流来读取URL的响应
            br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            exception = "发送 POST 请求出现异常！" + e;
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        if (sb.toString().isEmpty()) {
            result = exception;
        } else {
            result = sb.toString();
        }
        return result;
    }

    public String CC_File_Post(String path, FileRequest param) {
        OutputStream out = null;
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();
        String exception = "";
        String result = "";
        try {
            // 定义数据分隔线
            String BOUNDARY = Long.toHexString(System.currentTimeMillis());
            String CRLF = "\r\n";
            URL url = new URL(path);
            HttpURLConnection conn = null;
            // 打开和URL之间的连接
            conn = (HttpURLConnection) url.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");    // POST方法
            conn.setConnectTimeout(15 * 1000);// 设置连接超时时间为5秒
            conn.setReadTimeout(20 * 1000);// 设置读取超时时间为20秒
            String tokens = "";
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("accessToken", ACCESSTOKEN);
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new DataOutputStream(conn.getOutputStream());
            // 发送请求参数
            StringBuffer sbff = new StringBuffer();
            Map<String,Object> paramMap = BeanUtil.beanToMap(param);
            paramMap.forEach((k,v)->{
                sbff.append("--").append(BOUNDARY).append(CRLF);
                sbff.append("Content-Disposition: form-data; name=\"" + k + "\"").append(CRLF);
                sbff.append(CRLF).append(v.toString()).append(CRLF);
            });
            sbff.append("--").append(BOUNDARY).append(CRLF);
            sbff.append("Content-Disposition: form-data; name=\"" + param.getFileName() + "\"; filename=\"" + param.getFileName() + "\"").append(CRLF);
            sbff.append("Content-Type:application/octet-stream").append(CRLF).append(CRLF);
            out.write(sbff.toString().getBytes());
            @Cleanup DataInputStream din = new DataInputStream(param.getFile().getInputStream());
            int bytes = 0;
            byte[] buff = new byte[1024];
            while ((bytes=din.read(buff)) != -1){
                out.write(buff,0,bytes);
            }
            out.flush();
            byte[] end = ("\r\n--"+BOUNDARY+"--\r\n").getBytes();
            out.write(end);
            out.flush();
            out.close();
            System.out.println("==============");
            System.out.println(conn.getResponseCode());
            // 定义BufferedReader输入流来读取URL的响应
            br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            exception = "发送 POST 请求出现异常！" + e;
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        if (sb.toString().isEmpty()) {
            result = exception;
        } else {
            result = sb.toString();
        }
        return result;
    }

    public String oaSendPost(String path, String token, String param) {
        OutputStreamWriter out = null;
        BufferedReader br = null;
        StringBuffer sb = new StringBuffer();
        String exception = "";
        String result = "";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = null;
            // 打开和URL之间的连接
            conn = (HttpURLConnection) url.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");    // POST方法
            conn.setConnectTimeout(15 * 1000);// 设置连接超时时间为5秒
            conn.setReadTimeout(20 * 1000);// 设置读取超时时间为20秒
            String tokens = "";
            // 设置通用的请求属性
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("token", token);
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream());
            // 发送请求参数
            BufferedWriter bw = new BufferedWriter(out);
            bw.write(param);
            // flush输出流的缓冲
            bw.flush();
            // 定义BufferedReader输入流来读取URL的响应
            br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            exception = "发送 POST 请求出现异常！" + e;
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        if (sb.toString().isEmpty()) {
            result = exception;
        } else {
            result = sb.toString();
        }
        return result;
    }

    /**
     * @Description //TODO GET请求方法
     * @Author T.han
     * @Date 2023/8/18 10:06
     * @Param path 地址   http://127.0.0.1/cloudcc/outoken?key1=value1&key2=value2
     * @return java.lang.String
     **/
    public static String sendGet(String path) {
        StringBuffer sb = new StringBuffer();
        String exception = "";
        String result = "";
        try {
            URL url = new URL(path);
            InputStream is = url.openStream();
            InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);
            String line;//读取数据
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            isr.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
            exception = "发送 GET 请求出现异常！" + e;
        }
        if (sb.toString().isEmpty()) {
            result = exception;
        } else {
            result = sb.toString();
        }
        return result;
    }

    /**
     * 创建用户
     * @param loginName
     * @param name
     * @param email
     * @param profileId
     * @param roleId
     * @param password
     * @return
     */
    public ServiceResult createUser(String loginName, String name, String email, String profileId, String roleId, String password) {
        ServiceResult sr = new ServiceResult();
        JSONArray arry = new JSONArray();
        JSONObject obj = new JSONObject();
        //拼接 parObj 参数
        JSONObject parObj = new JSONObject();
        parObj.put("serviceName", "createUser"); //服务名
        parObj.put("loginName", loginName); //
        parObj.put("name", name); //
        parObj.put("email", email); //
        parObj.put("profileId", profileId); //
        parObj.put("roleId", roleId); //
        parObj.put("password", password); //
        parObj.put("sendEmail", "0"); //

        try {
            path = URL + "openApi/common";
            String relStr = CCPost(path, parObj.toString());
            JSONObject relObj = new JSONObject();
            relObj = JSONObject.fromObject(relStr);
            log.info("createUser------------:"+relObj);
            String result = relObj.getString("result");
            String returnInfo = relObj.getString("returnInfo");
            sr.put("result",result);
            sr.put("returnInfo",returnInfo);


        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("createUser= " + e);
        }
        return sr;
    }


}
